package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.BindTeachplanMediaDto;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TeachplanServiceImpl implements TeachplanService {

    @Autowired
    TeachplanMapper teachplanMapper;

    @Autowired
    TeachplanMediaMapper teachplanMediaMapper;
    //查询课程计划分支
    @Override
    public List<TeachplanDto> findTeachplanTree(long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }
    //新增或修改课程计划
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        Long id = saveTeachplanDto.getId();
        if (id==null){
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            Long courseId=teachplan.getCourseId();
            Long parentId=teachplan.getParentid();
            Integer count = getTeachplanCount(courseId, parentId);
            teachplan.setOrderby(count+1);
            teachplanMapper.insert(teachplan);
        }else{
           //修改
            Teachplan teachplan =teachplanMapper.selectById(id);
            BeanUtils.copyProperties(saveTeachplanDto,teachplan);
            teachplanMapper.updateById(teachplan);
        }
    }
    //删除课程计划
    @Transactional
    @Override
    public void deleteTeachplan(Long id){
        Teachplan teachplan = teachplanMapper.selectById(id);
        Integer grade = teachplan.getGrade();
        if (grade==1){//删除章
            LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getParentid,id);//查询表中是否有行的parentId等于删除章的id
            Integer count = teachplanMapper.selectCount(queryWrapper);
            if (count>0){
                XueChengPlusException.cast("课程计划信息还有子级信息，无法操作");
            }
            teachplanMapper.deleteById(id);
        }else{//删除小节
            LambdaQueryWrapper<TeachplanMedia> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(TeachplanMedia::getTeachplanId,id);
            teachplanMediaMapper.delete(queryWrapper);//delete * from teachplan_media where teachplan_id=#{id}
            teachplanMapper.deleteById(id);
        }
    }
    @Transactional
    @Override
    public void upTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        int orderby = teachplan.getOrderby();
        if (orderby==1){
            XueChengPlusException.cast("该章节已在第一位无法移动");
        }else {
            //先获取排序的对象
            LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(Teachplan::getOrderby,orderby-1).eq(Teachplan::getParentid,teachplan.getParentid());
            Teachplan teachplanSwap = teachplanMapper.selectOne(queryWrapper);
            LambdaQueryWrapper<Teachplan> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(Teachplan::getOrderby,orderby).eq(Teachplan::getParentid,teachplan.getParentid());
            Teachplan teachplan1 = teachplanMapper.selectOne(queryWrapper1);
            //再进行更新操作
            teachplanSwap.setOrderby(orderby);
            teachplan1.setOrderby(orderby-1);
            teachplanMapper.updateById(teachplanSwap);
            teachplanMapper.updateById(teachplan1);
        }
    }
    @Transactional
    @Override
    public void downTeachplan(Long id) {
        Teachplan teachplan = teachplanMapper.selectById(id);
        int orderby = teachplan.getOrderby();
        Long parentId=teachplan.getParentid();
        LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getParentid,parentId);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        if (orderby==count){
            XueChengPlusException.cast("该章节已在最后一位无法移动");
        }else {
            //先获取排序的对象
            LambdaQueryWrapper<Teachplan> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(Teachplan::getOrderby,orderby+1).eq(Teachplan::getParentid,parentId);
            Teachplan teachplan1 = teachplanMapper.selectOne(queryWrapper1);
            LambdaQueryWrapper<Teachplan> queryWrapper2=new LambdaQueryWrapper<>();
            queryWrapper2.eq(Teachplan::getOrderby,orderby).eq(Teachplan::getParentid,parentId);
            Teachplan teachplan2 = teachplanMapper.selectOne(queryWrapper2);
            //再进行更新操作
            teachplan1.setOrderby(orderby);
            teachplan2.setOrderby(orderby+1);
            teachplanMapper.updateById(teachplan1);
            teachplanMapper.updateById(teachplan2);
        }
    }
    //绑定课程计划视频
    @Transactional
    @Override
    public TeachplanMedia associationMedia(BindTeachplanMediaDto bindTeachplanMediaDto) {
        Long teachplanId = bindTeachplanMediaDto.getTeachplanId();
        Teachplan teachplan = teachplanMapper.selectById(teachplanId);
        if (teachplan==null){
            XueChengPlusException.cast("该教学计划不存在");
        }
        if (teachplan.getGrade()!=2){
            XueChengPlusException.cast("只能在课程计划的小节添加视频");
        }
        //删除原有视频
        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>()
                .eq(TeachplanMedia::getTeachplanId, teachplanId));
        //绑定添加的视频
        TeachplanMedia teachplanMedia=new TeachplanMedia();
        teachplanMedia.setCourseId(teachplan.getCourseId());
        teachplanMedia.setTeachplanId(teachplan.getId());
        teachplanMedia.setCreateDate(LocalDateTime.now());
        teachplanMedia.setMediaId(bindTeachplanMediaDto.getMediaId());
        teachplanMedia.setMediaFilename(bindTeachplanMediaDto.getFileName());
        teachplanMediaMapper.insert(teachplanMedia);
        return teachplanMedia;
    }
    //解除绑定
    @Override
    public void unbindMedia(String mediaId,Long teachPlanId) {

        teachplanMediaMapper.delete(new LambdaQueryWrapper<TeachplanMedia>()
                .eq(TeachplanMedia::getMediaId,mediaId)
                .eq(TeachplanMedia::getTeachplanId,teachPlanId));
    }

    //获取排序order最大值
    public Integer getTeachplanCount(Long courseId,Long parentId){
        LambdaQueryWrapper<Teachplan> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId,courseId);
        queryWrapper.eq(Teachplan::getParentid,parentId);
        List<Teachplan> teachplans = teachplanMapper.selectList(queryWrapper);
        if (teachplans.size()==0){
            return 0;
        }
        //转成orderBy元素的list集合[1,2,3,4...]
        List<Integer> orderBy = teachplans.stream().map(Teachplan::getOrderby).collect(Collectors.toList());
        Collections.sort(orderBy);//排序
        return orderBy.get(orderBy.size() - 1);//返回order最大的值，新增的order+1
    }
}
